import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import config from '../config';
import { useUser } from '../context/UserContext.jsx';
import { login, getProfile } from '../api/user';

const Login = ({ onLogin }) => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { setUser } = useUser();

  const handleFinish = async (values) => {
    setLoading(true);
    try {
      const data = await login(values);
      if (data.code === 200 && data.data && data.data.token) {
        localStorage.setItem('token', data.data.token);
        // 登录成功后获取用户信息
        const profileData = await getProfile();
        if (profileData.code === 200 && profileData.data && profileData.data.user) {
          setUser(profileData.data.user);
        }
        message.success('登录成功');
        onLogin();
      } else {
        message.error(data.msg || '登录失败');
      }
    } catch (e) {
      message.error('登录失败');
    }
    setLoading(false);
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #e0e7ff 0%, #f5f6fa 100%)',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
    }}>
      <div style={{ marginBottom: 32, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <img src={config.LOGO_URL} alt="logo" style={{ height: 56, marginBottom: 12, borderRadius: 12, boxShadow: '0 2px 8px #e5e6eb' }} />
        <div style={{ fontSize: 26, fontWeight: 700, color: '#222d3a', letterSpacing: 2, marginBottom: 8 }}>{config.PROJECT_NAME}</div>
        <div style={{ color: '#888', fontSize: 15 }}>欢迎登录，开启你的高效创作之旅！</div>
      </div>
      <Card style={{ width: 400, borderRadius: 16, boxShadow: '0 4px 24px #e0e7ff', border: 'none' }}>
        <div style={{ fontWeight: 600, fontSize: 20, textAlign: 'center', marginBottom: 28 }}>账号登录</div>
        <Form layout="vertical" onFinish={handleFinish} autoComplete="off">
          <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}> 
            <Input autoFocus size="large" placeholder="请输入用户名" allowClear />
          </Form.Item>
          <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}> 
            <Input.Password size="large" placeholder="请输入密码" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading} size="large" style={{ borderRadius: 8, fontWeight: 600, fontSize: 16, transition: 'all 0.2s' }}>登录</Button>
          </Form.Item>
        </Form>
        <div style={{ textAlign: 'center', marginTop: 16 }}>
          没有账号？ <a onClick={() => navigate('/register')}>去注册</a>
        </div>
      </Card>
    </div>
  );
};

export default Login; 